<template>
    <el-upload :disabled="status == 'details'" :class="{ 'upload-dzs': true, 'upload-dzs-phone': isPhone , 'is-disabled' : status == 'details' }" drag :action="action" :multiple="multiple"
        :file-list="fileList" :limit="limit" :before-upload="beforeUpload" :on-success="handleSuccess"
        :on-exceed="handleExceed" :auto-upload="autoUpload" :on-change="changeFile" :on-remove="handleRemove" :show-file-list="true">
        <el-icon size="50"><UploadFilled /></el-icon>
        <div class="el-upload__text" v-if="!isPhone">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__text" v-else><em>点击上传文件</em></div>
        <div class="el-upload__tip" slot="tip">
            <div>只能上传不超过 {{ maxSize / 1024 / 1024 }}M 的{{ fileType.join("、") }}文件</div>
            <div v-if="limit > 1">最多上传 {{ limit }} 个文件</div>
        </div>
    </el-upload>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import type { fileInfo } from "./@types";
import type { UploadProps } from 'element-plus';
import { ElMessage } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';

const emit = defineEmits(["update:value", "change", "upload-success", "upload-remove"]);
const props = defineProps({
    action: {
        type: String,
        default: () => {
            return "#"
        }
    },
    /**最多上传文件*/
    limit: {
        type: Number,
        default: () => {
            return 1
        }
    },
    /**最大上传大小*/
    maxSize: {
        type: Number,
        default: () => {
            return 5 * 1024 * 1024
        }
    },
    /**上传文件类型*/
    fileType: {
        type: Array,
        default: () => {
            return ["doc", "docx", "ppt", "pptx", "zip", "rar", "pdf", "xls", "xlsx", "txt", "jpg", "png", "jpeg"]
        }
    },
    /**原始文件列表*/
    value: {
        type: [Array<fileInfo | string>, String],
        default: () => {
            return []
        }
    },
    /**是否自动上传*/
    autoUpload: {
        type: Boolean,
        default: () => {
            return true
        }
    },
    /**是否手机端*/
    isPhone: {
        type: Boolean,
        default: () => {
            return false
        }
    },
    status: {
        type: String,
        default: () => {
            return 'add'
        }
    },
    uploadFun : {
        type: Function,
        default: () => {
            return (fileInfo: fileInfo, success: Function) => {

            }
        }
    },
    openUploadFun: {
        type: Boolean,
        default: () => {
            return false
        }
    }
})

const multiple = ref(false);
const fileList = ref<fileInfo[]>([]);

/**上传之前*/
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    let fileType = file.name.split(".")[1];
    if (props.fileType.indexOf(fileType) == -1) {
        ElMessage.error(`上传文件格式不正确`);
        return false;
    }
    if (file.size > props.maxSize) {
        ElMessage.error(`上传文件大小不能超过 ${props.maxSize / 1024 / 1024}MB!`);
        return false;
    }
    return true;
}
/**上传成功*/
const handleSuccess: UploadProps['onSuccess'] = (res, file) => {
    let fileInfo = {
        name: file.name,
        path: res.path ? res.path : "",
        uploadUrl: res.url ? res.url : "",
        uid: file.uid,
        formItem: "upload-file",
        status: "success",
    };
    fileList.value.push(fileInfo);
    emit("update:value", fileList.value);
    emit("change", fileList.value);
}
/**文件改变*/
const changeFile: UploadProps['onChange'] = (files) => {
    props.uploadFun(files, handleSuccess);
    if (props.autoUpload || props.openUploadFun) return;
    let fileInfo = {
        name: files.name,
        path: files.url,
        uploadUrl: files.url,
        uid: files.uid,
        status: "success",
        fromItem: "upload-file",
        file: files.raw
    };
    fileList.value.push(fileInfo);
    emit("update:value", fileList.value);
    emit("change", fileList.value);
}
/**超出文件个数限制时的钩子*/
const handleExceed: UploadProps['onExceed'] = (files, fileList) => {
    ElMessage.warning(`当前限制选择 ${props.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
}

// 删除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    let index = fileList.value.findIndex(item => item.uid == uploadFile.uid);
    fileList.value.splice(index, 1);
    emit("change", fileList.value);
    emit("update:value", fileList.value);
    emit("upload-remove", fileList.value);
}

watch(() => props.limit, (newValue) => {
    multiple.value = newValue > 1;
}, {
    immediate: true
})

watch(() => props.value, (newValue) => {
    if(!newValue){
        fileList.value = [];
        return ;
    }
    if(typeof newValue == "string"){
        fileList.value = [{
            name: newValue,
            url: newValue,
            uid: new Date().getTime() + Math.random(),
            status: "success"
        }]
        return ;
    }
    if(newValue && typeof newValue[0] == "string"){
        fileList.value = newValue.map((item) => {
            return {
                uid: new Date().getTime() + Math.random(),
                name : item ,
                url: item,
                status: "success",
                fromItem: "upload-file"
            } as fileInfo;
        })
        return ;
    }
    fileList.value = newValue as fileInfo[];
}, {
    immediate: true
})

</script>
<style scoped lang="scss">
.upload-dzs-phone {
    width: 100%;

    :deep(.el-upload) {
        width: 100%;

        .el-upload-dragger {
            width: 100%;
        }
    }
}
.is-disabled{
    :deep(.el-upload) {
        display: none;
    }
}
</style>